import { Button, Card, Dropdown, Input, Popconfirm, Space, Spin, Table, Tree, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { useState, useEffect, useRef, useContext } from 'react'
import Api from '../../../../../utils/api';
//import CztApi from '../../../../../utils/apis/CztApi'
import dynamicColumnApi from '../../../../../utils/apis/dynamicColumnApi';
import _ from 'lodash';
import ScrollTable from '../../../../common/ScrollTable';
import { data } from 'browserslist';
import { BrowserRouter, Route } from 'react-router-dom';
import CztEdit from '../CztHandle/CztEdit';
import { useHistory, Switch } from 'react-router-dom';
import pubsub from 'pubsub-js';
import FetchHelper from '../../../../../utils/helper/fetch-helper';
import WaiBuZhuanJiaApi from '../../../../../utils/apis/WaiBuZhuanJiaApi';
import columns from './columns';
import managerContext from '../../Entry/managerContext';


export default function Wbzjsj(props) {
    const [category, setCategory] = useState();

    const [cztData, setCztData] = useState();
    const [category2, setCategory2] = useState();
    const [total, setTotal] = useState();
    const [allColumns, setAllColumns] = useState();
    const [loading, setLoading] = useState();
    
    const {setLooktype}=useContext(managerContext);

    const rootRef = useRef();

    const [params, setParams] = useState({
        pageSize: 10,
        pageNum: 1,
        //cztMiddle: '公共服务设施'
    });

    useEffect(() => {
        Api.getWbzjsj().then(datas => {
            setCategory(datas)
        })
    }, [])

    useEffect(() => {
        Api.getCztCategroy2().then(datas => {
            setCategory2(datas)

        })
    }, [])

   /* 
   --外部专家数据类型
    */
    const [wbsjlx, setWbsjlx] = useState("气象数据");
    /* 
   --数据表格类型匹配
    */
   const [bgcolumns, setBgcolumns] = useState([]);

    const [node, setNode] = useState(null);
    // console.log('wbsjlx', wbsjlx)
    // console.log('node',node)


    useEffect(() => {
        setLoading(true);
        let promise;
        console.log('3',params)
        setLooktype(wbsjlx);
        if (wbsjlx==="气象数据") {
            promise = WaiBuZhuanJiaApi.qxlist(params);
            setBgcolumns(columns(wbsjlx));
        } else if(wbsjlx==="灾害结果"){
            promise = WaiBuZhuanJiaApi.pglist(params)
            setBgcolumns(columns(wbsjlx));
        }
        promise?.then(resp => {
          console.log('resp456',resp)
            setCztData(resp.rows)
            setTotal(resp.total);

        }).finally(e => {
            setLoading(false)
        })
    }, [wbsjlx, node,setLooktype,params])
    

    //新增

    const items = category2
    // 导出数据地址
    // const url = '/admin-api/ybyj/cztjcb/exportLike?columnNames=wbsjlx&key=公共服务设施';


    const tableCols = allColumns?.[params.cztSmall || params.cztMiddle] || [];
    //Excel表导入
    const message = '';

    props = {
        name: 'file',
        action: `/admin-api/ybyj/${wbsjlx==='灾害结果'?'dizhenData':'rysdsc'}/import`,
        headers: {
            authorization: 'authorization-text',
        },
        beforeUpload(file) {
            const isValidFormat = file.type === 'application/vnd.ms-excel';
            

            if (!isValidFormat) {
                message.error('只能上传 .xls格式的文件!');
            }
          

            return isValidFormat 
        },
        onChange(info) {
            //console.log('node',info)
            if (info.file.status === 'done') {
                message.success(`${info.file.name} 文件上传成功`);
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 文件上传失败`);
                alert(`数据表格可能与本数据表不一致，最好先导出一份数据，使用其模板写入数据后在进行上传`)
            }
        },

        // onChange(info) {
        //     if (info.file.status !== 'uploading') {
        //         console.log(info.file, info.fileList);
        //     }
        //     if (info.file.status === 'done') {
        //         message.success(`${info.file.name} 文件上传成功`);

        //     } else if (info.file.status === 'error') {
        //         message.error(`${info.file.name} 文件上传失败`);
        //     }
        // },
    };
    //编辑
    //设置按键跳转路径
    const history = useHistory();
    const cztHandleEdit = (record) => {
         history.push(`/manager/WbzjsjEdit/${record.id}`)

    }

    //查看

    const cztHandleLook = (record) => {
        history.push(`/manager/WbzjsjLook/${record.id}`)
    }

    //新增
    // const [key,setKey]=useState()
    const [keyPath, setKeyPath] = useState();
    const cztAddDatas = (keyPath) => {
        // history.push(`/manager/cztAdd/${keyPath[2]}--${keyPath[1]}--${keyPath[0]}`)
        history.push(`/manager/WbzjsjAdd/${keyPath}`)
    }

    //删除按键

    const deleteHandle = (record) => {

        // const newcztData = cztData.filter(function (arr) {
        //     return arr.id !== record.id
        // })

        // FetchHelper.deleteJson(`/admin-api/ybyj/cztjcb/` + record.id).then(() => alert('删除成功')).catch(error => alert("删除失败") + error)


        // setCztData(newcztData)
    }
    // debugger
    //搜索
    const formCztData = cztData

    const onSearch = (value) => {
        let a=wbsjlx==='气象数据'?{ps:value}:{ckdd:value}
        setParams(params => {
            console.log("params",params,a)
            return {
                ...params,
                ...a,
                pageNum: 1
            }
        });

    }
    // console.log('params',params)
    // const [messageApi,contentHolder]=Message.useMessage();

    const handleJudge = (node, keyPath) => {
        if (node?.tag !== "cztxl") {
            window.alert('请选择小类')
        }
        else {
            const keyPath = node?.key
            cztAddDatas(keyPath)
        }
    }





    return <div className='layout-h h100'>
        <Card size='small' className='h100' style={{
            width: 240,
            marginRight: 12,
            overflowX: "auto",
            overflowY: "auto"

        }} title={"外部专家数据列表"}>
            {category && <Tree className='categray-tree' selectedKeys={[wbsjlx]}
                treeData={category} blockNode
                defaultExpandAll
                rootStyle={{color:'#aaa'}}
                onSelect={(selectedKeys, { node }) => {
                    console.log("12",selectedKeys,{node})
                    setWbsjlx(selectedKeys[0])
                    setNode(node)

                }}
                fieldNames={{
                    title: 'title',
                    key: 'title'
                }}
            />}

        </Card>
        <Card size="small" className='h100 fill w0' style={{
            position: "relative",
        }} bodyStyle={{

            display: "flex",
            flexDirection: "column",
            height: "100%"
        }}>
            <div style={{
                marginBottom: 12,
                display: 'flex',
                alignItems: "center",
                justifyContent: "space-between"
            }}>

                <Space>
                    <>
                        <Button onClick={() => cztAddDatas(keyPath)}>新增</Button>
                        <Upload {...props}>
                            <Button disabled={!wbsjlx} icon={<UploadOutlined />}>数据导入</Button>
                        </Upload>
                        {/* <Button disabled={!wbsjlx} type="primary" key="download" onClick={() => {
                            fetch(`/admin-api/ybyj/${wbsjlx==='灾害结果'?'dizhenData/export':'rysdsc/export'}?columnNames=${node?.tag}&key=${node.key}`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json;charset=UTF-8'
                                }
                            }).then(response => response.blob()).then(blob => {
                                const a = document.createElement("a");
                                a.download = `${wbsjlx==='灾害结果'?"data.zip":"data.zip"}`;
                                a.href = URL.createObjectURL(blob);
                                a.click();
                            }).catch(error => console.log(error))
                        }}>数据导出</Button> */}
                    </>
                </Space>

                <div>
                    <Input.Search placeholder='输入名称查找'
                        allowClear
                        enterButton={true}
                        onSearch={onSearch}
                    />
                </div>
            </div>
            <div ref={rootRef} className="fill h0">
                {<ScrollTable style={{
                    // border:"1px solid #ddd"
                }}
                    loading={loading}
                    parentNode={rootRef.current}
                    size='small'
                    bordered
                    dataSource={cztData}
                    scroll={{
                        x: 320 + _.sumBy(tableCols, 'width'),
                    }}
                    columns={[
                       ...bgcolumns,
                        {
                            title: '操作',
                            key: 'caozuo',
                            width: 260,
                            fixed: "right",
                            render: (text, record) => {
                                return <Space size="middle">
                                    <Button onClick={e => { cztHandleLook(record) }}>查看</Button>

                                    <Button onClick={e => { cztHandleEdit(record) }}>编辑</Button>

                                    <Popconfirm title="确定删除吗?" onConfirm={e => deleteHandle(record)}>
                                        {/* <Button onComfir={e => { deleteHandle(record) }}>删除</Button> */}
                                        <Button>删除</Button>
                                    </Popconfirm>
                                </Space>

                            }
                        },

                    ].map(item => {
                        return {
                            ...item,
                        }
                    })}

                    pagination={{
                        current: params.pageNum,
                        pageSize: params.pageSize,
                        total,

                        // simple: true
                    }}
                    onChange={({ current }) => {
                        setParams(params => {
                            return {
                                ...params,
                                pageNum: current
                            }
                        })
                    }}
                // size='small'
                />}
            </div>
        </Card>
    </div>;
}